package tiruvury.InterviewPrep.HelperClasses;

import java.util.Stack;

public class StackWithMin extends Stack<Integer>
{
	private static final long serialVersionUID = 1L;
	Stack<MinStackNode> minStack = new Stack<MinStackNode>();

	public void Push(int data)
	{
		/*
		 * CODINGERROR: stack.peek() returns EmptyStackException if the stack is
		 * empty. Check the size.
		 */
		MinStackNode minSoFar = (minStack.size() > 0) ? minStack.peek() : null;
		if (minSoFar == null || data < minSoFar.data)
		{
			minStack.push(new MinStackNode(data, 1));
		}
		else if (data == minSoFar.data)
		{
			minSoFar.count++;
		}
		super.push(data);
	}

	public Integer Pop()
	{
		MinStackNode minSoFar = (minStack.size() > 0) ? minStack.peek() : null;
		Integer poppedNode = (super.size() > 0) ? super.pop() : null;
		if (poppedNode != null && minSoFar != null)
		{
			if (poppedNode.intValue() == minSoFar.data)
			{
				if (minSoFar.count == 1)
				{
					minStack.pop();
				}
				else
				{
					minSoFar.count--;
				}
			}
		}
		return poppedNode;
	}

	public Integer Min()
	{
		MinStackNode mstkNode = minStack.peek();
		if (mstkNode != null)
		{
			return mstkNode.data;
		}

		return Integer.MAX_VALUE;
	}
}
